<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form)
      },
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="单据单号" prop="deliveryBillNo">
              <ElInputBox :data="form" dataName="deliveryBillNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="发货类型" prop="deliveryType">
              <ElSelectBox :data="form" dataName="deliveryType" :options="[
                {
                  label: '成品发货',
                  value: 1,
                },
                {
                  label: '半成品发货',
                  value: 2,
                }
              ]" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="客户名称" prop="customerCode" isRules>
              <ElSelectBox :data="form" dataName="customerCode" placeholder="请选择" :options="options.customer"
                :disabled="!isEdit" @changeBtn="selectCustomer" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <template v-if="form.customerCode">
          <CellBox title="快递信息" isTop>
            <div class="expressDelivery list-r-12 dlText-90">
              <SenderAddress :data="form" :isEdit="isEdit" />
            </div>
          </CellBox>
          <CellBox title="产品信息" isTop>
            <template #btn>
              <el-link icon="Filter" type="primary" @click="() => {
                pupAdd.state = true
                getAddTbody()
              }">选择产品</el-link>
            </template>
            <ProductInfo :data="setProductRow()" :form="form" />
          </CellBox>
          <CellBox title="单据明细" isTop>
            <TableBoxMx :data="{
              disabled: !isEdit,
              tbody: form.fhMxList,
              thead: [
                {
                  label: '公司名称',
                  prop: 'receiveCompanyName',
                  align: 'left',
                  width: 120,
                },
                {
                  label: '收货人',
                  prop: 'receiverName',
                  align: 'center',
                  width: 80,
                },
                {
                  label: '联系电话',
                  prop: 'receiveTelephone',
                  align: 'center',
                  width: 120,
                },
                {
                  label: '详细地址',
                  prop: 'receiveAddress',
                  align: 'left',
                  width: 220,
                },
                {
                  label: '发货数量',
                  prop: 'deliveryQuantity',
                  align: 'center',
                  width: 120,
                  formProp: 'fhMxList',
                  formType: 'number',
                },
                {
                  label: '生产日期',
                  prop: 'produceDate',
                  align: 'center',
                  width: 160,
                  formProp: 'fhMxList',
                  formType: 'day',
                },
                {
                  label: '送货日期',
                  prop: 'expressTime',
                  align: 'center',
                  width: 160,
                  formProp: 'fhMxList',
                  formType: 'day',
                },
                {
                  label: '费用承担',
                  prop: 'costAssumeDepartment',
                  align: 'center',
                  width: 160,
                  formProp: 'fhMxList',
                  formType: 'select',
                  options: proxy.$optionsArr.courierFeeType
                },
                {
                  label: '收货方式',
                  prop: 'receivingWay',
                  align: 'center',
                  width: 120,
                  formProp: 'fhMxList',
                  formType: 'select',
                  options: options.receivingWay
                },
                {
                  label: '快递方式',
                  prop: 'expressWay',
                  align: 'center',
                  width: 120,
                  formType: 'select',
                  options: options.expressWay
                },
                // {
                //   label: '付费方式',
                //   prop: 'paymentWay',
                //   align: 'center',
                //   width: 120,
                //   formType: 'select',
                //   options: options.paymentWay
                // },
                // {
                //   label: '费用部门',
                //   prop: 'costAssumeDepartment',
                //   align: 'center',
                //   width: 120,
                //   formType: 'select',
                //   options: options.costAssumeDepartment
                // },
                {
                  label: '快递单号',
                  prop: 'expressBillNo',
                  align: 'center',
                  width: 120,
                  formType: 'text',
                },
                {
                  label: '快递费用',
                  prop: 'expressCost',
                  align: 'center',
                  width: 120,
                  formType: 'number',
                },
                // {
                //   label: '快递重量',
                //   prop: 'expressGoodsWeight',
                //   align: 'center',
                //   width: 160,
                //   formType: 'number',
                // },
                // {
                //   label: '快递件数',
                //   prop: 'expressGoodsCount',
                //   align: 'center',
                //   width: 160,
                //   formType: 'number',
                // },
                {
                  label: '备注',
                  prop: 'deliveryMxRemark',
                  align: 'left',
                  width: 260,
                  formType: 'text',
                },
              ],
              //表格-列表搜索
              operation: [
                {
                  label: '删除',
                  icon: 'Delete',
                },
              ],
            }">
            </TableBoxMx>
            <SelectAddress :customerCode="form.customerCode" :selectable="(row: any) => {
              const _arr = form.fhMxList.map((el: any) => el.receiveAddressCode)
              return !_arr.includes(row.receiveAddressCode)
            }" isCheckbox class="m-t-8" @selectBtn="(arr: any) => {
              const _row = {
                receiveAddressCode: '', // 收方信息-收货人编码（收货地址代码）
                receiveCompanyName: '', // 收方信息-收方公司名称
                receiverName: '', // 收方信息-收方姓名
                receiveTelephone: '', // 收方信息-收方电话
                receiveProvinceCode: '', // 收方信息-收方省编码
                receiveCityCode: '', // 收方信息-收方市编码
                receiveAreaCode: '', // 收方信息-收方区编码
                receiveAddress: '', // 收方信息-收方详细地址
                receivingWay: '', // 其他信息-收货方式（字典明细项）
                expressWay: '', // 其他信息-送货方式（快递公司）（字典明细项）
                expressBillNo: '', // 其他信息-快递单号
                expressTime: '', // 其他信息-快递时间（送货时间）
                expressCost: null, // 其他信息-快递费用
                paymentWay: '', // 其他信息-付款方式（字典明细项）
                costAssumeDepartment: '', // 其他信息-费用承担部门
                expressGoodsWeight: null, // 其他信息-快递物品重量（公斤数）
                expressGoodsCount: null, // 其他信息-快递物品件数
                deliveryQuantity: null, // 发货数量
                deliveryBoxCount: null, // 发货箱数
                kilogramQuantity: null, // 公斤数
                deliveryMxRemark: '' // 发货明细备注
              }
              const _arr = arr.map((el: any) => ({
                ..._row,
                receiveAddressCode: el.receiveAddressCode,
                receiveCompanyName: el.companyName || '',
                receiverName: el.contactPersonName,
                receiveTelephone: el.contactTelephone,
                receiveProvinceCode: el.province,
                receiveCityCode: el.city,
                receiveAreaCode: el.country,
                receiveAddress: el.detailedAddress,
              }))
              form.fhMxList.push(..._arr)
            }">
              <el-button class="wAuto" icon="Plus">选择收货地址</el-button>
            </SelectAddress>
          </CellBox>
        </template>
      </div>
    </template>
  </DetailsFormBox>
  <SelectCom :pup="pupAdd" :table="pupAdd.tableAdd" @searchBtn="getAddTbody" @selectBtn="(arr: any) => {
    const _row = arr[0]
    data.form.productSpecificationCode = _row?.productSpecificationCode
    data.form.produceDate = _row?.saleOrders[0]?.produceDate || proxy.$day(new Date)
    data.form.saleOrders = [_row?.saleOrders[0]]
  }">
    <template #search="{ search }">
      <ElFormItemBox label="产品名称" prop="productName">
        <ElInputBox :data="search" dataName="productName" />
      </ElFormItemBox>
    </template>
    <template #saleOrders="{ row }">
      {{row.saleOrders.map((el: any) => `${el.xieYiShuHao}【${el.waitDeliveryQuantity}${el.productUnit}】`).join('、')}}
    </template>
  </SelectCom>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import SenderAddress from '../template/SenderAddress.vue'; // 寄方信息
import ProductInfo from '../template/ProductInfo.vue'; // 产品信息
import SelectAddress from '../template/SelectAddress.vue'; // 选择地址
import { useListComponent } from '../pageTs.ts'; // 引入逻辑
const { dataInfo, options } = useListComponent();
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    deliveryType: 1, // 基本信息-发货类型：1成品发货，其他待定
    customerCode: "", // 基本信息-客户编码
    companyName: "", // 寄方信息-寄方公司名称
    senderName: "", // 寄方信息-寄方姓名
    senderTelephone: "", // 寄方信息-寄方电话
    provinceCode: "", // 寄方信息-寄方省编码
    cityCode: "", // 寄方信息-寄方市编码
    areaCode: "", // 寄方信息-寄方区编码
    address: "", // 寄方信息-寄方详细地址
    deliveryRemark: "", // 发货备注
    productSpecificationCode: "", // 产品信息-产品型号code
    produceDate: proxy.$day(new Date), // 产品信息-生产日期
    saleOrders: [], // 产品信息-成品型号关联的SaleOrder列表
    fhMxList: [] // 发货明细数据存储集合对象
  },
});
const isEdit = ref(true)
//选择客户
const selectCustomer = (isInitialized: boolean = false) => {
  const _form = data.form
  getProductOrder()//获取客户产品信息
  //初始化
  _form.fhMxList = []
}
//获取产品信息
const setProductRow = () => {
  return options.product.find((el: any) => el.productSpecificationCode === data.form.productSpecificationCode) || {}
}
//获取成品信息
const getAddTbody = () => {
  const _table = pupAdd.tableAdd
  _table.tbody = proxy.$filterArr(options.product, (row: any) => {
    return row.productName.includes(_table.search.productName)
  })
}
const pupAdd: any = reactive({
  state: false,
  typeName: 0,
  title: `选择成品`,
  tbody: [],
  tableAdd: {
    rowKey: 'productSpecificationCode',
    search: {
      productName: '',
    },
    tbody: [],
    thead: [
      {
        label: '成品名称',
        prop: 'productName',
        align: 'left',
        width: 400,
      },
      {
        label: '型号规格',
        prop: 'productSpecificationName',
        align: 'left',
        width: 120,
      },
      {
        label: '产品版本',
        prop: 'productVersion',
        align: 'center',
        width: 80,
      },
      {
        label: '库存数量',
        prop: 'stockQuantity',
        align: 'center',
        width: 140,
      },
      {
        label: '单位',
        prop: 'productUnit',
        align: 'center',
        width: 120,
      },
      {
        label: '待发货订单',
        prop: 'saleOrders',
        align: 'left',
        width: null,
      },
    ],
  },
});
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();

//获取数据
const getForm = async () => {
  const _query: any = route.query
  setLoading()
  //是否新建
  if (!!!_query.code) {
    data.loading = false
    return
  }
  proxy.$api.OrderBusniess.GetSaleOrderDeliveryDetail({
    queryBy: 0,
    queryValue: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = ['1', '2'].includes(_query.type)
      data.form = res
      selectCustomer()
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
//获取客户产品信息
const getProductOrder = () => {
  proxy.$api.OrderBusniess.GetSaleOrderDeliveryMxByCustomerCode({
    queryBy: 0,
    queryValue: data.form.customerCode,
  })
    .then((res: any) => {
      options.product = proxy.$flattenObjectArray(res.products, 'productSpecifications', (row: any) => ({
        ...row,
        saleOrders: row.saleOrders.map((el: any) => ({
          ...el,
          cartonWeight: row.cartonWeight,//包装信息-每个纸箱重量
          eachWeight: row.eachWeight,//包装信息-每个（套）标签重量
          eachBoxQuantity: row.eachBoxQuantity,//包装信息-每箱数量
          productUnit: row.productUnit,//产品单位
          productVersion: row.productVersion,//产品版本
        }))
      }))
    })
    .catch(() => {

    });
};

const saveBtn = (form: any) => {
  if (form.saleOrders.length === 0) {
    proxy.$message('未选择产品，请完善！', 'error')
    return
  } else if (form.fhMxList.length === 0) {
    proxy.$message('未选地址信息，请完善！', 'error')
    return
  }
  proxy.$api.OrderBusniess.CreateSaleOrderDeliveryBatch(form)
    .then((res: any) => {
      _sun()
    })
    .catch(() => { });
  function _sun() {
    closeBtn('保存成功')
  }
  function _setState(row: any) {
    proxy.$api.OrderBusniess.SureSaleOrderDelivery({
      entityID: row.deliveryID, //
    })
      .then((res: any) => {
        _sun()
      })
      .catch(() => {
        _sun()
      });
  }
};
const closeBtn = (message?: string) => {
  if (message) {
    proxy.$message(message)
  }
  sendMsg('save', true);
  // getForm()
  window.close();
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};
import { getCustomer, getDictionary, getOrganization } from '@/utils/optionsArr.ts';
onMounted(() => {
  getForm();
  //客户
  getCustomer(options, 'customer');
  //收货方式
  getDictionary(options, 'receivingWay', {
    DictionaryCode: 'ReceivingType',
  });
  //快递方式
  getDictionary(options, 'expressWay', {
    DictionaryCode: 'SendingType',
  });
  //付费方式
  getDictionary(options, 'paymentWay', {
    DictionaryCode: 'LogisticsPaidType',
  });
  //费用部门
  getOrganization(options, 'costAssumeDepartment');
});
</script>
